package com.baozun.controller;

import java.util.LinkedHashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.baozun.model.TChat;
import com.baozun.model.TChatEx;
import com.baozun.model.TChatExample;
import com.baozun.model.TFriend;
import com.baozun.model.TUser;
import com.baozun.service.ChatService;
import com.baozun.service.FriendService;
import com.baozun.service.UserService;
import com.baozun.util.CommonConst;
import com.baozun.util.ModelMapUtil;
import com.baozun.util.PageData;
import com.baozun.util.SessionUtil;

/**
 * 
 * @Title:
 * @Company:宝尊电子商务有限公司
 * @Description:
 * @Author:xiaozhou.zhou
 * @Since:2015年1月27日
 * @Copyright:Copyright (c) 2014
 * @ModifyDate:
 * @Version:1.1.0
 */
@Controller
@RequestMapping("/chat")
public class ChatController {
    
    @Autowired
    private ChatService chatService;
    @Autowired
    private UserService userService;
    @Autowired
    private FriendService friendService;
    
    private int pageSize = 20;
    private int currentPage = 1;
    
    /**
     * 
     * @param request
     * @param response
     * @return
     * @Description:
     */
    @RequestMapping("/chat_main")
    public String chatMain(HttpServletRequest request) {
        return "chat/chat_main";
    }

    
    /**
     * 聊天列表
     * 
     * @param request
     * @param response
     * @return
     * @Description:
     */
    @RequestMapping("/chat_list")
    public String chatList(ModelMap model, HttpServletRequest request, HttpServletResponse response) {
        TUser user = (TUser) SessionUtil.getAttribute(request, CommonConst.SESSION_USER, TUser.class);
        String content = request.getParameter("content");// 根据聊天内容查找聊天记录
        // 从聊天记录表中取出数据（）
        TChatExample record = new TChatExample();
        record.createCriteria().andStUserIdFromEqualTo(user.getStUserId());
        record.or(record.createCriteria().andStUserIdToEqualTo(user.getStUserId()));
        record.setOrderByClause(TChat.DT_CREATE_TIME);
        List<TChat> chatList = chatService.getList(record);
        LinkedHashMap<String, TChatEx> chatExMap = new LinkedHashMap<String, TChatEx>();// 有顺序的map
        
        // 这里的chat都是一条记录一条数据，要对这些数据进行组装
        for (TChat chat : chatList) {
            // 判断是否为答复
            boolean isAnswer = chat.getStUserIdFrom().equals(user.getStUserId()) ? true : false;
            
            TChatEx chatEx = null;
            String stSelfId = null;
            String stFriendId = null;
            String stName = null;
            String stRemark = null;
            if (isAnswer) {
                chatEx = chatExMap.containsKey(chat.getStUserIdFrom()) ? chatExMap.get(chat.getStUserIdFrom()) : new TChatEx(chat.getStChatId());
                stSelfId = chat.getStUserIdFrom();
                stFriendId = chat.getStUserIdTo();
            } else {
                chatEx = chatExMap.containsKey(chat.getStUserIdFrom()) ? chatExMap.get(chat.getStUserIdTo()) : new TChatEx(chat.getStChatId());
                stSelfId = chat.getStUserIdTo();
                stFriendId = chat.getStUserIdFrom();
            }
            // 根据好友ID先查询在TFriend中是否存在数据（可能该好友数据被删除）
            TFriend friend = friendService.findByFriendId(stSelfId, stFriendId);
            if (friend != null) {
                if (user.getStUserId().equals(friend.getStUserIdRequest())) {
                    stName = friend.getStNameResponse();
                    stRemark = friend.getStRemarkResponse();
                } else {
                    stName = friend.getStNameRequest();
                    stRemark = friend.getStRemarkRequest();
                }
            } else {
                // 好友为空，表示该好友数据已经被删除
                TUser userFriend = userService.get(stFriendId);
                stName = userFriend.getStName();
            }
            // 得到聊天记录的时候，其中包含了接收或答复
            chatEx.setStChatId(stFriendId);
            chatEx.setStSelfId(stSelfId);
            chatEx.setStFriendId(stFriendId);
            chatEx.setStName(stName);
            chatEx.setStRemark(stRemark);
            chatEx.setDtTime(chat.getDtCreateTime());
            chatEx.setStChatContent(chat.getStChatContent());
            chatExMap.put(chatEx.getStChatId(), chatEx);
        }
        new ModelMapUtil(model).put("chatExMap", chatExMap);
        return "chat/chat_list";
    }
    
    /**
     * 进入聊天窗口
     * 
     * @param request
     * @param response
     * @return
     * @Description:
     */
    @RequestMapping("/chat_detail")
    public String chatDetail(ModelMap model, HttpServletRequest request, HttpServletResponse response) {
        TUser user = (TUser) SessionUtil.getAttribute(request, CommonConst.SESSION_USER, TUser.class);// 当前登录用户
        String stFriendId = request.getParameter("stFriendId");// 聊天记录的对象用户主键
        // 得到好友数据
        TUser friendUser = userService.get(stFriendId);
        // 查询两人聊天数据
        TChatExample record = new TChatExample();
        // 当前登录用户为接收方
        record.createCriteria().andStUserIdFromEqualTo(stFriendId).andStUserIdToEqualTo(user.getStUserId());
        // 当前登录用户为发送方
        record.or(record.createCriteria().andStUserIdFromEqualTo(user.getStUserId()).andStUserIdToEqualTo(stFriendId));
        // 查出前十条数据
        PageData<TChat> infoList = chatService.getPageListByExample(record, pageSize, currentPage);
        new ModelMapUtil(model).put("pageSize", pageSize).put("currentPage", currentPage).put(CommonConst.REQUEST_PAGE_DATA, infoList).put("friendUser", friendUser);
        return "chat/chat_detail";
    }
    
    
    @RequestMapping("/add_chat.do")
    public void addChat(HttpServletRequest request, HttpServletResponse response) {
        
    }
}
